from Customer.db_connector import DBUtils


class TransactionPrinter:
    def __init__(self):
        self.db = DBUtils()
        self.db.connect()

    def __del__(self):
        self.db.disconnect()

    def get_full_transactions(self, card_id=None):
        """
        获取完整交易记录
        参数:
            card_id: 可选的卡号筛选条件
        返回:
            完整交易记录列表
        """
        query = "SELECT * FROM tradeinfo"
        params = []

        if card_id:
            query += " WHERE cardID = %s"
            params.append(card_id)

        query += " ORDER BY tradeDate DESC"

        try:
            return self.db.execute_query(query, params)
        except Exception as e:
            print(f"查询失败: {e}")
            return None

    def get_full_information(self, card_id=None):
        """获取完整账户信息"""
        query = """
        SELECT 
            deposit.customerid AS customerid,  # 明确指定列来源和别名
            cardinfo.name AS name,
            cardinfo.cardID AS cardID,
            deposit.balance AS balance,
            deposit.openDate AS openDate,
            cardinfo.status AS status
        FROM deposit
        JOIN cardinfo ON deposit.savingid = cardinfo.savingid
        """
        params = []
        if card_id:
            query += " WHERE cardinfo.cardID = %s"
            params.append(card_id)
        query += " ORDER BY deposit.savingid DESC"
        return self.db_execute_query(query, params)

    def print_full_informations(self, transactions):
        """
        输出
        """
        if not transactions:
            print("没有找到记录")
            return

        # 定义列格式
        headers = ["卡号", "交易日期", "类型", "金额", "流水号", "备注"]
        col_formats = [
            ("{:<19}", "cardID"),  # 卡号左对齐，19字符宽度
            ("{:<19}",
             lambda t: t['tradeDate'].strftime('%Y-%m-%d %H:%M') if hasattr(t['tradeDate'], 'strftime') else t[
                 'tradeDate']),  # 日期
            ("{:^8}", "tradeType"),  # 类型居中对齐
            ("{:>12}", lambda t: f"{float(t['tradeMoney']):.2f}元"),  # 金额右对齐带两位小数
            ("{:<22}", "transactionID"),  # 流水号左对齐
            ("{:<20}", lambda t: t.get('remark', ''))  # 备注左对齐
        ]

        # 计算分隔线长度
        line_length = sum(len(f[0].format("")) for f in col_formats) + 5  # 5个竖线字符
        separator = "=" * line_length

        # 打印表头
        print("\n" + separator)
        header_parts = []
        for i, (header, (fmt, _)) in enumerate(zip(headers, col_formats)):
            header_parts.append(fmt.format(header))
        print("|" + "|".join(header_parts) + "|")
        print(separator)

        # 打印数据行
        for t in transactions:
            row_parts = []
            for fmt, getter in col_formats:
                if callable(getter):
                    value = getter(t)
                else:
                    value = t[getter]
                row_parts.append(fmt.format(value))
            print("|" + "|".join(row_parts) + "|")

        # 打印表尾
        print(separator)
        print(f"共找到 {len(transactions)} 条记录\n")


# 使用示例
if __name__ == "__main__":
    printer = TransactionPrinter()

    # 查询特定卡号的交易记录
    card_transactions = printer.get_full_transactions("1010357600000002")
    printer.print_full_transactions(card_transactions)